<template>
  <div class="app-container txtIN">
    <!-- 访客查询 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
    >
      <el-form-item :label="$t('common.csearchWord')" prop="visitorSearchValue">
        <el-input
          v-model="queryParams.visitorSearchValue"
          size="small"
          :placeholder="$t('celler.searchValue')"
          style="width: 220px"
          clearable
          @change="clearKeyword()"
        />
      </el-form-item>

      <el-form-item :label="$t('celler.interTime')">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 340px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          :start-placeholder="$t('common.cstartTime')"
          :end-placeholder="$t('common.cendTime')"
          @change="clearDate()"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >{{ $t("common.csearch") }}</el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("common.creset")
        }}</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 访客操作 -->
    <el-row :gutter="10" class="mb8" style="display: flex; align-items: center">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['systems:visitor:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addCellerInfo"
        >{{ $t("common.caddkey") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['systems:visitor:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="leadingOutData"
        >{{ $t("operating.export") }}</el-button>
      </el-col>
      <!-- <right-toolbar
        :show-search.sync="showSearch"
        :columns="columns"
        @queryTable="initVisitor"
      /> -->
    </el-row>

    <!--表格-->
    <el-table
      ref="multipleTable"
      class="datalist"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <!-- :height="tableMaxHeight" -->
      <!-- <el-table-column type="index" width="50" /> -->
      <!-- <el-table-column type="selection" min-width="50" align="center" /> -->
      <el-table-column
        v-if="columns[0].visible"
        key="name"
        width="80"
        prop="name"
        :label="$t('celler.name')"
      />
      <el-table-column
        v-if="columns[1].visible"
        key="idNum"
        prop="idNum"
        :label="$t('celler.idNum')"
        width="180"
      />
      <el-table-column
        v-if="columns[2].visible"
        key="phoneNum"
        prop="phoneNum"
        :label="$t('celler.phoneNum')"
        width="120"
      />
      <el-table-column
        v-if="columns[3].visible"
        key="remark"
        prop="remark"
        :label="$t('celler.remark')"
      />
      <el-table-column
        v-if="columns[4].visible"
        key="interTime"
        prop="interTime"
        :label="$t('celler.interTime')"
        width="180"
      />
      <el-table-column
        v-if="columns[5].visible"
        key="leaveTime"
        prop="leaveTime"
        :label="$t('celler.datetime')"
        width="180"
      />
      <el-table-column
        v-if="columns[6].visible"
        key="tagId"
        prop="tagId"
        :label="$t('celler.tagId')"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        v-if="columns[7].visible"
        key="contactsName"
        prop="contactsName"
        :label="$t('celler.contactsName')"
      />
      <!-- 操作解绑 -->
      <el-table-column :label="$t('operating.operating')">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-edit"
            type="text"
            @click="updateVisitor(scope.row)"
          >{{ $t("common.cupdate") }}</el-button>

          <el-button
            v-hasPermi="['systems:visitor:leave']"
            icon="el-icon-delete"
            type="text"
            @click="unBinding(scope.row)"
          >{{ $t("celler.leave") }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="initVisitor"
    />

    <!-- 弹窗内容 -->
    <el-dialog
      :title="titleDialog"
      :visible.sync="editVisible"
      :close-on-click-modal="false"
      width="600px"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :label-position="labelPosition"
      >
        <el-row :gutter="18">
          <el-col :span="12">
            <el-form-item :label="$t('celler.name')" prop="name">
              <el-input
                v-model="form.name"
                :placeholder="$t('operating.rule')"
                :disabled="inputDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isAdd" :label="$t('celler.idNum')" prop="idNum">
              <el-input
                v-model="form.idNum"
                :placeholder="$t('operating.rule')"
                :disabled="inputDisabled"
                @blur="getCellerInfoByCardID"
              />
            </el-form-item>
            <el-form-item v-if="!isAdd" :label="$t('celler.idNum')">
              <el-input
                v-model="form.idNum"
                :placeholder="$t('operating.rule')"
                :disabled="inputDisabled"
                @blur="getCellerInfoByCardID"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isAdd" :label="$t('celler.phoneNum')" prop="phoneNum">
              <el-input v-model="form.phoneNum" />
            </el-form-item>
            <el-form-item v-if="!isAdd" :label="$t('celler.phoneNum')">
              <el-input v-model="form.phoneNum" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('celler.contactsName')"
              prop="contactsName"
            >
              <el-select
                v-model="form.contactsName"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in deptObjData"
                  :key="item.resourceId"
                  :label="item.name"
                  :value="item.resourceId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('celler.remark')" prop="remark">
              <el-input v-model="form.remark" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('celler.rfidId')" prop="tagId">
              <el-input v-model="form.tagId" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-show="!isSearch">
          <el-button type="primary" @click="onSubmit">{{
            $t("common.cok")
          }}</el-button>
          <el-button @click="onCancel">{{ $t("operating.cancel") }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import AES from '@/utils/aes.js'
import {
  visitorList,
  addCeller,
  removeBinding,
  getIDCardInfo,
  getAllDeptDetail,
  downloadFile
} from '@/api/cy.js'
export default {
  data() {
    return {
      total: 0, // 总页数
      dateRange: [], // 来访日期范围
      tableData: [], // 访客表格数据
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        visitorSearchValue: undefined
      },

      showSearch: true, // 是否显示条件查询
      // 设置表格行列是否显示
      columns: [
        { key: 0, label: this.$i18n.t('celler.name'), visible: true },
        { key: 1, label: this.$i18n.t('celler.idNum'), visible: true },
        { key: 2, label: this.$i18n.t('celler.phoneNum'), visible: true },
        { key: 3, label: this.$i18n.t('celler.remark'), visible: true },
        { key: 4, label: this.$i18n.t('celler.interTime'), visible: true },
        { key: 5, label: this.$i18n.t('celler.datetime'), visible: true },
        { key: 6, label: this.$i18n.t('celler.tagId'), visible: true },
        { key: 7, label: this.$i18n.t('celler.contactsName'), visible: true }
      ],

      editVisible: false, // 编辑框是否可见
      removeBindingVisible: true, // 解除编辑框
      statusValue: '', // 访问状态

      searchValue: '', // 模糊查询参数
      cur_page: 1, // 当前所在页
      size_page: '10', // 每页显示的数据条数
      /** ***********编辑页面相关*************/
      labelPosition: 'right', // 表单label文字对齐方式
      inputDisabled: false,
      /** **************访客数据提交**************/
      cellerPhoto: '',
      name: '', // 用户姓名
      idNum: '', // 身份证号码
      phoneNum: '', // 访客手机号码
      remark: '', // 来访目的
      tagId: '', // 绑定标签ID
      rfidId: '',
      contactsName: '', // 接待人员姓名
      /** **************访客数据提交**************/
      deptObjData: [],
      /** ***********编辑页面相关*************/

      tableMaxHeight: window.innerHeight - 240,

      removeBindingIDCardNo: '',
      removeBindingTag: '',

      serach_editVisible: false, // 搜索弹出框显示与影藏
      serach_name: '', // 弹框姓名
      serach_idNum: '', // 弹出身份证号
      serach_phoneNum: '', // 电话号码
      serach_contactsName: '', // 接待人员
      serach_remark: '', // 采访目的地
      serach_rfidId: '', // RFID
      serach_cellerPhoto: '', // 图片

      // 表单参数
      form: {
        name: '',
        idNum: '',
        phoneNum: '',
        contactsName: '',
        remark: '',
        tagId: ''
      },
      // 表单校验
      rules: {
        name: [
          {
            required: true,
            message: this.$i18n.t('celler.nameRule'),
            trigger: 'blur'
          }
        ],
        idNum: [
          {
            required: true,
            // pattern: /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/,
            message: this.$i18n.t('celler.idNumRule'),
            trigger: 'blur'
          }
        ],
        phoneNum: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: this.$i18n.t('celler.phoneNumRule'),
            trigger: 'blur'
          }
        ],
        contactsName: [
          {
            required: true,
            message: this.$i18n.t('celler.contactsNameRule'),
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: this.$i18n.t('celler.remarkRule'),
            trigger: 'blur'
          }
        ],
        tagId: [
          {
            required: true,
            message: this.$i18n.t('celler.tagIdRule'),
            trigger: 'blur'
          }
        ]
      },

      isSearch: false,
      titleDialog: '',
      chooseIdx: [], // 选中的文本框
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      value1: [],
      isAdd: false // 是否是添加
    }
  },
  computed: {
    getcardID() {
      return this.form.idNum.replace(/(\w{6})\w*(\w{4})/, '$1******$2')
    }
  },
  mounted() {
    this.initVisitor()
    this.initReceptionist()
  },

  methods: {
    phonenumber(val) {
      let text = ''
      if (val) {
        text = val.substring(0, 3) + '****' + val.substring(7)
      }
      return text
    },
    formCardID(val) {
      let cardVal
      if (val) {
        cardVal = val.replace(/(\w{6})\w*(\w{4})/, '$1******$2')
      }
      return cardVal
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.initVisitor()
    },

    /** 重置搜索操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 初始化访客记录
    initVisitor() {
      visitorList(this.choseDateRange(this.queryParams, this.dateRange)).then(
        res => {
          this.total = res.total
          this.tableData = res.rows
        }
      )
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.chooseIdx = selection.map(item => item.idx)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    updateVisitor(row) {
      console.log(row)
      this.form.name = row.name
      // this.form.idNum = this.formCardID(row.resourceId)
      // this.form.phoneNum = this.phonenumber(row.phoneNum)
      this.form.idNum = row.idNum
      this.form.phoneNum = row.phoneNum
      this.form.contactsName = row.contactsName
      this.form.remark = row.remark
      this.form.tagId = row.tagId
      // this.form.visitorPhoto = this.tableData[0].visitorPhoto;
      this.editVisible = true
      this.isAdd = false
      this.form.idx = row.idx
    },

    /**
     * 确认添加
     */
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let idNumAes; let phoneNumAes
          if (this.form.idNum) {
            const idCard = this.form.idNum.trim()
            console.log(idCard)
            idNumAes = AES.encrypt(idCard)
          }
          if (this.form.phoneNum) {
            const isPhone = this.form.phoneNum.trim()
            console.log(isPhone)
            phoneNumAes = AES.encrypt(isPhone)
          }

          const param = {
            type: 'visitor',
            name: this.form.name, // 用户姓名
            idNum: idNumAes, // 身份证号码
            phoneNum: phoneNumAes, // 访客手机号码
            remark: this.form.remark, // 来访目的
            tagId: this.form.tagId, // 绑定标签ID
            contactsId: this.form.contactsName // 接待人员姓名
            // visitorPhoto: this.form.cellerPhoto, // 访客照片
          }
          if (!this.isAdd) {
            param.idx = this.form.idx
          } else {
            if (this.form.idx) {
              delete this.form.idx
            }
          }

          addCeller(param).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.editVisible = false
              // this.resetForm("form");
              setTimeout(() => {
                this.initVisitor()
              }, 1200)
            } else {
              this.msgError(res.msg)
            }
          })
        }
      })
    },

    /**
     * 取消添加
     */
    onCancel() {
      this.editVisible = false
      this.resetForm('form')
    },
    /**
     * 关闭dialog的回调函数
     */
    closeDialog() {
      this.resetForm('form')
    },

    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },

    /** 解除绑定 */
    unBinding(row) {
      const param = { idx: row.idx }
      removeBinding(param).then(res => {
        if (res.code === 200) {
          // if (this.isSearch) {
          //   this.editVisible = false
          //   this.isSearch = false
          // }
          this.msgSuccess(res.msg)
          setTimeout(() => {
            this.searchValue = ''
            this.initVisitor()
          }, 2000)
        } else {
          this.msgError(res.msg)
        }
      })
    },

    /*
    添加访客信息
    */
    addCellerInfo() {
      this.form = {
        name: '',
        idNum: '',
        phoneNum: '',
        contactsName: '',
        remark: '',
        tagId: ''
      }
      this.isAdd = true
      this.editVisible = true
      this.isSearch = false
      this.titleDialog = this.$i18n.t('celler.addVisit')

      // this.loadIdentityInfo();
    },

    // 获取身份证信息,读卡器码刷码使用，目前作废
    loadIdentityInfo() {
      getIDCardInfo('txt').then(res => {
        this.name = res.data.name
        this.idNum = res.data.idNumber
      })
      getIDCardInfo('fig').then(res => {
        this.cellerPhoto = 'data:image/bmp;base64,' + res.data.fig
      })
    },

    /**
     * 初始化接待人员
     */
    initReceptionist() {
      // 获取表格中的数据
      getAllDeptDetail().then(res => {
        this.deptObjData = res.data
        const allStffer = []
        for (let i = 0; i < this.deptObjData.length; i++) {
          if (this.deptObjData[i].type == 'staff') {
            allStffer.push(this.deptObjData[i])
          }
        }
        this.deptObjData = allStffer
      })
    },

    /*
    导出表格中的内容
     */
    leadingOutData() {
      // 根据搜索条件导出内容
      const urlPath = '/system/visitor/report?token=' + Cookie.get('token')
      const filename = 'visitor_' + new Date().getTime() + '.xls'
      downloadFile(urlPath, filename)
    },

    // 直接解除绑定
    handleRemoveBinding(index, row) {
      const param = { condition: row.idNum }
      this.$api.cellermanage.removeBinding(param).then(res => {
        const RES = this.responseUse(res, true)
        this.removeBindingVisible = false
        this.getData()
      })
    },

    getCellerInfoByCardID(event) {
      // 需要检查是否处于查找模式
      // 查找模式，只输入了身份证号码
      if (
        this.name === '' &&
        this.phoneNum === '' &&
        this.remark === '' &&
        this.tagId === '' &&
        this.contactsName === '' &&
        this.idNum !== ''
      ) {
        this.$api.cellermanage.getCellerInfoByCardID(this.idNum).then(res => {
          const RES = this.responseUse(res)

          // console.log("根据身份证号码查找到的信息：", RES);
          if (RES.length === 0) {
            this.v_MyMessage(this.$t('Notice.noDataHasBeenFound'), 'info')
          } else if (RES.length > 1) {
            this.v_MyMessage(
              this.$t('Notice.queryMultipleVisitorInformation'),
              'warning'
            )
          } else if (RES.length === 1) {
            this.name = RES[0].name // 用户姓名
            // this.idNum = RES[0].idNum; // 身份证号码
            this.phoneNum = RES[0].phoneNum // 访客手机号码
            this.remark = RES[0].remark // 来访目的
            this.tagId = RES[0].tagId // 绑定标签ID
            this.rfidId = RES[0].rfidId
            this.contactsName = RES[0].contactsName // 接待人员姓名
          }
        })
      }
    },

    closeRemoveBindingDialog() {
      this.removeBindingIDCardNo = ''
      this.removeBindingTag = ''
    },

    /**
     * 清空表单
     */
    clearFrom() {
      this.name = ''
      this.idNum = ''
      this.phoneNum = ''
      this.remark = ''
      this.tagId = ''
      this.contactsName = ''
      this.cellerPhoto = ''
      // 将输入框全都设置为可编辑状态
      this.inputDisabled = false
      this.rfidId = ''
    },
    /** ***************************************************************************/

    /*
    查看访客信息详情
     */
    // handleDetail(index, row) {
    //   // console.log(index, row);
    //   this.name = row.name
    //   this.idNum = row.idNum
    //   this.phoneNum = row.phoneNum
    //   this.remark = row.remark
    //   this.tagId = row.tagId
    //   this.contactsName = row.contactsId
    //   this.cellerPhoto = row.visitorPhoto

    //   this.editVisible = true
    //   this.inputDisabled = true
    // },

    // 确认解除绑定
    removeBinding() {
      const param = { condition: this.removeBindingTag }
      this.$api.cellermanage.removeBinding(param).then(res => {
        // const RES = this.responseUse(res, true)
        this.removeBindingVisible = false
        this.getData()
      })
    },

    // /*
    //  * 解除绑定
    //  */
    // handleRemoveBinding1(index, row) {
    //   this.removeBindingIDCardNo = row.idNum;
    //   this.removeBindingTag = row.rfidId;

    //   // 先显示解除编辑框
    //   this.removeBindingVisible = true;
    // },

    // 弹出狂接触绑定
    handleRemoveBinding4() {
      const param = { condition: this.serach_idNum }
      this.$api.cellermanage.removeBinding(param).then(res => {
        // const RES = this.responseUse(res, true)
        this.removeBindingVisible = false
        this.getData()
      })
      this.serach_editVisible = false
    },

    handleRemoveBinding2() {
      // alert(1)
      // this.$api.cellermanage.getIDCardInfo('txt').then(res => {
      //   let RES = this.responseUse(res);
      //   this.removeBindingIDCardNo = RES.idNumber;
      this.removeBindingVisible = true
      // })
    },

    /**
     * 获取访客列表
     */
    getData() {
      let param
      if (this.searchValue === '') {
        param = {
          pageNum: this.cur_page,
          pageSize: this.size_page
        }
      } else {
        param = {
          pageNum: this.cur_page,
          pageSize: this.size_page,
          param: {
            visitorSearchValue: this.searchValue
          }
        }
      }
      this.$api.cellermanage.getCellerList(param).then(res => {
        const RES = this.responseUse(res)
        this.tableDataNum = RES.totalSize
        this.tableData = RES.content
      })
    },

    clearKeyword() {
      if (!this.queryParams.visitorSearchValue) {
        delete this.queryParams.visitorSearchValue
        this.queryParams.pageNum = 1
        // this.initVisitor()
      }
    },
    clearDate() {
      if (!this.dateRange) {
        this.dateRange = []
        this.queryParams.pageNum = 1
        // this.initVisitor()
      }
    },

    /**
     * 初始化一些内容
     */
    init() {
      // 获取表格中的数据
      this.getData()

      this.$api.historydisplayinfo.getAllDeptDetail().then(res => {
        const RES = this.responseUse(res)
        this.deptObjData = RES
        const allStffer = []
        for (let i = 0; i < this.deptObjData.length; i++) {
          if (this.deptObjData[i].type == 'staff') {
            allStffer.push(this.deptObjData[i])
          }
        }
        this.deptObjData = allStffer
      })
    },
    // 刷新窗口
    windowRefresh: function() {
      this.tableMaxHeight = window.innerHeight - 240
    }
  }
}
</script>
<style scoped >
/deep/ .el-form-item {
  margin-bottom: 10px;
}

/deep/ .el-dialog__body {
  padding: 8px 24px;
}

/deep/ .el-table .cell {
  white-space: nowrap !important;
}
</style>

<style>
.el-upload--text {
  /* background-color: #fff; */
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  box-sizing: border-box;

  height: 180px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.el-upload--text .el-icon-upload {
  font-size: 67px;
  color: #97a8be;
  margin: 40px 0 16px;
  line-height: 50px;
}

.el-upload--text {
  color: #97a8be;
  font-size: 14px;
  text-align: center;
}

.el-upload--text em {
  font-style: normal;
}

/* .el-col-12 {
  height: 58px;
} */
.visitor {
  display: none;
}
.cardInput {
  background-color: #ffffff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: none;
  padding: 0 15px;
  -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}
 .el-input__inner {
      height: 40px!important;
}

</style>
